package masterOutputMakers;

import static java.lang.System.err;
import static java.lang.System.exit;
import static java.lang.System.out;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import system.FileSystem;
import system.Writer;

/**
 *
 * @author Peter Cappello
 */
public class StandardMasterOutputMaker implements Writer
{
    @Override
    public void write(FileSystem fileSystem, int numWorkers)
    {
        try
        {
            // open Master file for output
            FileOutputStream fileOutputStream = fileSystem.getFileOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream( fileOutputStream );
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter( dataOutputStream ) );
            for ( int fileNum = 1; fileNum <= numWorkers; fileNum++ )
            {
                // open Worker output file for input
                FileInputStream fileInputStream = fileSystem.getWorkerOutputFileInputStream( fileNum );
                DataInputStream dataInputStream = new DataInputStream( fileInputStream );
                BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( dataInputStream ));
    
                for ( String line; ( line = bufferedReader.readLine() ) != null; )
                {
                    // append line to output file
                    bufferedWriter.write( line );
                    bufferedWriter.newLine();
                }
                // close Worker output file
                bufferedReader.close();
                dataInputStream.close();
                fileInputStream.close();
            }
            // close Master output file
            bufferedWriter.close();
            dataOutputStream.close();
            fileOutputStream.close();
        }
        catch ( Exception exception )
        {
            err.println( "SimpleFileWriter.write: Error: " + exception.getMessage());
            exit( 1 );
        }
    } 
}
